package com.baturu.vin.benz.service.impl.util;

import com.baturu.vin.benz.consts.BenzLandEnum;
import com.baturu.vin.benz.dal.dao.BenzI18nDAO;
import com.baturu.vin.benz.dto.BenzI18nDTO;
import com.baturu.vin.benz.utils.ThreadUtil;
import com.baturu.vin.enums.LangEnum;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * BenzI18nService
 * 国际化service
 *
 * @author majianming
 * @date 2019-04-08 17:34
 */
@Service
public class BenzI18nService implements InitializingBean {

    private static Map<String, String> LANG_MAP_HASH_MAP = Maps.newHashMap();
    @Autowired
    private BenzI18nDAO benzI18nDAO;

    public String trans(String code) {
        BenzLandEnum landEnum = ThreadUtil.getBenzLandEnum();
        if (Objects.isNull(landEnum)) {
            landEnum = BenzLandEnum.getDefault();
        }
        String landCode = landEnum.getLandCode();
        return LANG_MAP_HASH_MAP.getOrDefault(landCode + "#" + code, code);

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        List<BenzI18nDTO> i18nDTOS = benzI18nDAO.loadAllTrans();
        LANG_MAP_HASH_MAP.clear();
        Map<String, List<BenzI18nDTO>> collect = i18nDTOS.stream().collect(Collectors.groupingBy(o -> o.getLangCode() + "#" + o.getCode()));
        collect.forEach((k, v) -> LANG_MAP_HASH_MAP.put(k, v.get(0).getDescription()));
    }

    public BenzLandEnum setEPCLand(LangEnum langEnum) {
        BenzLandEnum benzLandEnum = BenzLandUtil.transLand(langEnum);
        ThreadUtil.setLandEnum(benzLandEnum);
        return benzLandEnum;
    }

    public BenzLandEnum getBenzLangEnum() {
        return ThreadUtil.getBenzLandEnum();
    }
}


